<?php
 

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Db;
use think\Request;
use think\helper\Hash;
use app\user\model\Role;
use app\user\model\User as AdminUserModel;
use think\facade\Hook;

class Statistics extends Admin
{

    public function day(){
        $map    =   $this->getMap();
        if (!isAdmin()) {
            $map['agency_id']  = getAgencyId();
        } 
        $data   =   Db::table('day_total')->where($map)->order('id desc')->paginate();
        return ZBuilder::make('table')
        ->setTableName('day_total')
        ->hideCheckbox()
        ->setSearch(['agency_id','agency_name'])
        ->addColumns([
            ['date','日期'],
            ['agency_id','代理ID'],
            ['agency_level','代理等级'],
            ['agency_name','代理姓名'],
            ['invite_code','邀请码'],
            ['ratio','费率'],
            ['total_register','总注册数'],
            ['total_bind','总绑卡数'],
            ['total_amount','总交易金额'],
            ['total_gain','收益总计'],
            ['my_gain','直属收益'],
            ['sub_gain','二级收益'],
        ])
        ->setRowList($data)
        ->setPages($data->render())
        ->fetch();
    }

    public function add(){
        return ZBuilder::make('form')
        ->addFormItems([
            ['text', 'name', '姓名', '必填，中文'],
            ['text', 'tel', '手机号'],
            ['password', 'password', '密码', '必填，6-20位'],
            ['select', 'parent_id', '上级代理', '', $this->getParentAgency()],
            ['text','invite_code','邀请码','必填 , 长度6位数字'],
            ['number','ratio','费率','必填,例如0.004'],
          //  ['radio', 'status', '状态', '', ['禁用', '启用'], 1]
        ])
        ->setUrl('addPost')
        ->fetch();
    }

    public function addPost(Request $request){
        $param = $request->param();
        if($this->isInviteCodeExist($param['invite_code'])){
            $this->error('邀请码已存在');
        }
        if($this->isTelExist($param['tel'])){
            $this->error('手机号已存在');
        }
        if(strlen($param['password']) < 8){
            $this->error('密码至少8位');
        }
        $uid = Db::name('agency')->insertGetId([
            'name'        =>  $param['name'],
            'tel'         =>  $param['tel'],
            'password'    =>  Hash::make($param['password']),
            'parent_id'   =>  $param['parent_id'],
            'level'       =>  $param['parent_id'] == 0 ? 1:2,
            'invite_code' =>  $param['invite_code'],
            'ratio'       =>  $param['ratio'],
            'created_at'  =>  NOW_TIME,
            'updated_at'  =>  NOW_TIME,
        ]);

        $data  = [
            'username'  => $param['tel'],
            'nickname'  => $param['name'],
            'role'      => '2',
            'password'  => $param['password'],
            'mobile'    => $param['tel'],
            'status'    => 1,
            'agency_id' => $uid,
        ];
        if (session('user_auth.role') != 1) {
            if ($data['role'] == session('user_auth.role')) {
                $this->error('禁止创建与当前角色同级的用户');
            }
            $role_list = Role::getChildsId(session('user_auth.role'));

            if (!in_array($data['role'], $role_list)) {
                $this->error('权限不足，禁止创建非法角色的用户');
            }
        }
        $user = AdminUserModel::create($data);
        Hook::listen('user_add', $user);
        action_log('user_add', 'admin_user', $user['id'], UID);

        Db::name('day_total')->insert([
            'date'          => date('Y-m-d'),
            'agency_id'     => $uid,
            'agency_name'   => $param['name'],
            'invite_code'   => $param['invite_code'],
            'agency_level'  => $param['parent_id'] == 0 ? 1:2,
            'ratio'         => $param['ratio'],
        ]);
        $this->success('成功');
    }

    public function edit($id = ''){
        $data = Db::name('agency')->where('id',$id)->find();

        if($this->request->isPost()){

            $param    = $this->request->param();
            $id       = $param['id'];
            
            $password = $param['password'];
            if( 0 < Db::name('agency')->where('tel',$param['tel'])->where('id','neq', $id )->count()){
                return $this->error('手机号已存在');
            }
            if( 0 < Db::name('agency')->where('invite_code',$param['invite_code'])->where('id','neq',$id )->count()){
                return $this->error('邀请码已存在');
            }
            $status   = $param['status'];
            if ($status == 'on') {
                $status = 1;
            }else{
                $status = 0;
            }
            Db::name('agency')->where('id',$id )->update([
                'name'        =>  $param['name'],
                'tel'         =>  $param['tel'],
                'password'    =>  $password,
                'parent_id'   =>  $param['parent_id'],
                'level'       =>  $param['parent_id'] == 0 ? 1:2,
                'invite_code' =>  $param['invite_code'],
                'ratio'       =>  $param['ratio'],
                'updated_at'  =>  NOW_TIME,
            ]);

            AdminUserModel::where('agency_id',$id)->update([
                'username'  => $param['tel'],
                'nickname'  => $param['name'],
                'password'  => Hash::make($password),
                'mobile'    => $param['tel'],
                'status'    => $status,
            ]);
            $this->success('成功');
        }

        return ZBuilder::make('form')
        ->addFormItems([
            ['hidden','id'],
            ['text', 'name', '姓名', '必填，中文',$data['name']],
            ['text', 'tel', '手机号' ,'' ,$data['tel']],
            ['password', 'password', '密码', '必填，6-20位',$data['password']],
            ['select', 'parent_id', '上级代理', '' , $this->getParentAgency(),$data['parent_id']],
            ['text','invite_code','邀请码','必填 , 长度6位数字',$data['invite_code']],
            ['text','ratio','费率','必填 , 例如0.004',$data['ratio']],
            ['switch','status','启用/禁用','',$data['status']],
        ])
            
        ->fetch();
    }


    public function editPost(){
    
    }

    private function getParentAgency(){
        $items  = Db::table('agency')->where('parent_id',0)->select();
        $arr    = [0 => '一级代理'];
        if(!empty($items)){
            foreach($items as $item){
                $res[$item['id']]  =   "姓名:{$item['name']}   |   手机:{$item['tel']}";
            }
            return array_merge($arr,$res);
        }
        return $arr;
    }

    private function isTelExist($tel){
        $count = Db::name('agency')->where('tel',$tel)->count();
        if($count > 0){
            return true;
        }
        return false;
    }


    private function isInviteCodeExist($code){
        $count = Db::name('agency')->where('invite_code',$code)->count();
        if($count > 0){
            return true;
        }
        return false;
    }

    
    public function myusers(){
        $map    =   $this->getMap();
        if (!isAdmin()) {
            $map['agency_id']  = getAgencyId();
        }else{
            $map['agency_id']  = 10000;
        }
        $data   =   Db::table('users')->where($map)->order('id desc')->paginate();
        return ZBuilder::make('table')
        ->setTableName('agency')
        ->hideCheckbox()
        ->addTopButton('add')
        ->addRightButton('edit')
        ->addRightButton('delete')
        ->setSearch(['tel','name'])
        ->addColumns([
            ['id','ID'],
            ['tel','手机号','callback',function($val){return hideMobile($val);}],
            ['name','姓名'],
            ['level','代理等级 (0代表普通用户) '],
            ['invite_code','邀请码'],
           // ['radio','佣金比例'],
            ['created_at','注册时间'],
            //['status','状态','switch'],
            ['right_button','操作']
        ])
        ->setRowList($data)
 
        ->setPages($data->render())
        ->fetch();
    }
}
